package com.xhl.oauth2.config.oauth2;

import com.xhl.oauth2.base.constant.Oauth2Constant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.annotation.Resource;


@Configuration
@EnableAuthorizationServer
//@ConfigurationProperties(prefix = "spring.security.oauth2")
public class MyAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Value("${spring.security.oauth2.clientId}")
    private String clientId;

    @Value("${spring.security.oauth2.clientSecret}")
    private  String clientSecret;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private UserDetailsService userDetailsService;

    /**
     * JWT的存储策略
     */
    @Resource
    private TokenStore jwtTokenStore;

    /**
     * JWT的转换器
     */
    @Resource
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    /**
     * 异常转换
     */
    @Resource
    private ResponseExceptionTranslator exceptionTranslator;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //这个好比账号
                .withClient(clientId)
                //授权同意的类型
                .authorizedGrantTypes("password", "refresh_token","authorization_code")
                //有效时间
                .accessTokenValiditySeconds(1800)
                .refreshTokenValiditySeconds(60 * 60 * 2)
                .resourceIds(Oauth2Constant.RESOURCE_ID)
                //配置redirect_uri,用于授权成功后跳转
                .redirectUris("http://localhost:8080/login")
                //作用域，范围
                .scopes(Oauth2Constant.OAUTH2_SCOPE_TYPE)
                //直接发放令牌
                .autoApprove(true)
                //密码
                .secret(new BCryptPasswordEncoder().encode(clientSecret));
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(jwtTokenStore)
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                .accessTokenConverter(jwtAccessTokenConverter)
                .exceptionTranslator(exceptionTranslator);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //允许客户端表单身份验证
        //对外发布认证入口(/oauth/token),认证通过服务端会生成一个令牌
        security.tokenKeyAccess("permitAll()")
                    //对外发布检查令牌的入口(/oauth/check_token)
                    .checkTokenAccess("permitAll()")
                    //允许用户通过表单方式提交认证,完成认证
                    .allowFormAuthenticationForClients();
    }
}
